from flask import g
from flask import render_template, current_app, jsonify
from flask import request
from flask import session

from info.models import User, News, Category
from info.modules.index import index_blue
from info.utils.commoms import user_login_data
from info.utils.response_code import RET


#  获取首页新闻列表信息
@index_blue.route('/newslist')
def get_news_list():
    """
    获取指定分类的新闻列表
    1. 获取参数
    2. 校验参数
    3. 查询数据
    4. 返回数据
    :return:
    """""
    #  获取参数
    cid = request.args.get('cid', 1)
    page = request.args.get('page', 1)
    per_page = request.args.get('per_page', 10)

    #  将参数转换成int类型，因为paginate里面的属性是整型
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        per_page = 10

    # 使用分页查询新闻列表数据
    try:
        #  判断分类编号是否不等于1
        filters = [News.status==0]
        #  cid为字符串
        if cid != "1":
            filters.append(News.category_id == cid)

        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='新闻列表内容查询失败')

    # 获取到分页对象中的内容
    current_page = paginate.page
    #  获取到总页数
    total_page = paginate.pages
    #  获取到查询出来的数据
    items = paginate.items

    #  将数据对象列表转换成字典
    newsList = []
    for news in items:
        newsList.append(news.to_dict())

    # 返回数据
    return jsonify(errno=RET.OK, errmsg='查询成功', totalPage=total_page, currentPage=current_page, newsList=newsList)


#  用户登陆数据，热门新闻排行，分类排行
@index_blue.route('/', methods=['GET', 'POST'])
@user_login_data
def index():
    # redis_store.set('name', 'xiaohua')
    # session['name']='xiaohu'
    # return render_template('hello')
    # #  通过session取出用户编号
    # user_id = session.get('user_id')
    # #  根据用户编号取出用户信息
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    #  用户的数据在公共模块中
    #  查询数据库中前十条新闻，按照点击量降序排序
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(10)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='新闻查询失败')

    # 将新闻对象列表转成字典列表
    click_news_list = []
    for click_news in news_list:
        click_news_list.append(click_news.to_dict())

    # 查询分类列表
    categories = None
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='新闻分类查询失败')

    # 将分类对象转成字典
    categories_list = []
    for category in categories:
        categories_list.append(category.to_dict())

    # 拼接数据并渲染到页面中
    data = {
        'user_info': g.user.to_dict() if g.user else '',
        'click_news_list': click_news_list,
        'categories_list': categories_list,
    }

    return render_template('news/index.html', data=data)


#  返回图标
@index_blue.route('/favicon.ico')
def get_web_log():
    return current_app.send_static_file('news/favicon.ico')
